<?php
// 设置允许的来源，这里假设允许来自 http://1.13.198.191:8081 的请求
// header("Access-Control-Allow-Origin: http://1.13.198.191:8081");
header("Access-Control-Allow-Origin: http://localhost:9528");
// 允许携带凭证
header("Access-Control-Allow-Credentials: true");
// 允许的HTTP方法
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
// 允许的请求头
header("Access-Control-Allow-Headers: Content-Type");

// 处理预检请求（OPTIONS）
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

// 连接数据库
require_once "./conn.php";
require_once "./usersession.php";

if ($conn->connect_error) {
    die(json_encode(["Code" => 200, "Ret" => "True", "Msg" => "Connection failed: " . $conn->connect_error]));
}

// 新增配置，后台用
$data = json_decode(file_get_contents("php://input"), true);
$name = $conn->real_escape_string($data['name']);
$addTime = date("Y-m-d H:i:s");
$modifyTime = date("Y-m-d H:i:s");
$settings = $conn->real_escape_string(json_encode($data['settings']));

// 检查是否存在同名配置
$checkSql = "SELECT COUNT(*) as count FROM configurations WHERE zhongkong_name = '$username' AND name = '$name'";
$result = $conn->query($checkSql);
$row = $result->fetch_assoc();

if ($row['count'] > 0) {
    echo json_encode(["Code" => 500, "Ret" => "True", "Msg" => "此配置名已存在"]);
} else {
    $sql = "INSERT INTO configurations (zhongkong_name, name, addTime, modifyTime, settings) VALUES ('$username', '$name', '$addTime', '$modifyTime', '$settings')";
    if ($conn->query($sql) === TRUE) {
        echo json_encode(["Code" => 200, "Ret" => "True", "Msg" => "配置新增成功"]);
    } else {
        echo json_encode(["Code" => 500, "Ret" => "True", "Msg" => "错误: " . $sql . "<br>" . $conn->error]);
    }
}

$conn->close();
